/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.system.api.feign.DuckweedRemoteUserService;
import com.pig4cloud.pigx.system.constant.EmailTemplateTypeEnum;
import com.pig4cloud.pigx.system.constant.FeedbackEnum;
import com.pig4cloud.pigx.system.dto.ArticleInformationDTO;
import com.pig4cloud.pigx.system.dto.MobileFeedbackDTO;
import com.pig4cloud.pigx.system.entity.Feedback;
import com.pig4cloud.pigx.system.entity.User;
import com.pig4cloud.pigx.system.mapstruct.FeedbackStruct;
import com.pig4cloud.pigx.system.service.FeedbackService;
import com.pig4cloud.pigx.system.util.SendEmailUtil;
import com.pig4cloud.pigx.system.vo.MobileFeedbackVO;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 反馈意见
 *
 * @author pigx code generator
 * @date 2022-10-12 20:03:36
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/feedback" )
@Api(value = "feedback", tags = "反馈意见管理")
public class FeedbackController {

    private final  FeedbackService feedbackService;

    /** 邮件发送工具类 */
    private final SendEmailUtil sendEmailUtil;

    private final DuckweedRemoteUserService duckweedRemoteUserService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param feedback 反馈意见
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('system_feedback_view')" )
    public R getFeedbackPage(Page page, Feedback feedback) {
        return R.ok(feedbackService.page(page, Wrappers.query(feedback)
				.orderByAsc("state")
				.orderByDesc("create_time")));
    }


    /**
     * 通过id查询反馈意见
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('system_feedback_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(feedbackService.getById(id));
    }

    /**
     * 新增反馈意见
     * @param feedback 反馈意见
     * @return R
     */
    @ApiOperation(value = "新增反馈意见", notes = "新增反馈意见")
    @SysLog("新增反馈意见" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('system_feedback_add')" )
    public R save(@RequestBody Feedback feedback) {
        return R.ok(feedbackService.save(feedback));
    }

    /**
     * 修改反馈意见
     * @param feedback 反馈意见
     * @return R
     */
    @ApiOperation(value = "修改反馈意见", notes = "修改反馈意见")
    @SysLog("修改反馈意见" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('system_feedback_edit')" )
    public R updateById(@RequestBody Feedback feedback) {

		feedback.setUpdateTime(LocalDateTime.now());
    	// 查询当前意见反馈的状态信息
		Feedback feedbackInfo = feedbackService.getOne(new LambdaQueryWrapper<Feedback>()
				.select(Feedback::getState)
				.eq(Feedback::getId, feedback.getId()));

		feedbackService.updateById(feedback);
		// 意见反馈被采纳采纳，发送邮件通知
		if (!feedbackInfo.getState().equals(FeedbackEnum.FeedbackState.HAS_BEEN_ADOPTED.getCode()) &&
				feedback.getState().equals(FeedbackEnum.FeedbackState.HAS_BEEN_ADOPTED.getCode())){
			R<User> user = duckweedRemoteUserService.getUserByUserId(feedback.getUid(), SecurityConstants.FROM_IN);

			ArticleInformationDTO articleInformationDTO = new ArticleInformationDTO();
			// 用户语言
			articleInformationDTO.setLanguageId(user.getData().getLanguageCode());
			// 意见反馈邮件模板编号
			articleInformationDTO.setArticleTypeCode(EmailTemplateTypeEnum.FEEDBACK_WAS_ACCEPTED.getArticleTypeCode());
			sendEmailUtil.sendEmail(null, null, user.getData().getEmail(), articleInformationDTO);
		}
		return R.ok();
    }

    /**
     * 通过id删除反馈意见
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除反馈意见", notes = "通过id删除反馈意见")
    @SysLog("通过id删除反馈意见" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('system_feedback_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(feedbackService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param feedback 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('system_feedback_export')" )
    public List<Feedback> export(Feedback feedback) {
        return feedbackService.list(Wrappers.query(feedback));
    }


	/**
	 * Dapp获取用户反馈意见列表
	 * @return R
	 */
	@ApiOperation(value = "Dapp获取用户反馈意见列表", notes = "Dapp获取用户反馈意见列表")
	@GetMapping("/app/getUserFeedbackList")
    public R<List<MobileFeedbackVO>> getUserFeedbackList(){
		// 查询登录用户
		PigxUser user = SecurityUtils.getUser();
		if (user == null){
			return R.failed();
		}

		List<Feedback> feedbackList = feedbackService.list(new LambdaQueryWrapper<Feedback>()
				.eq(Feedback::getUid, user.getId())
				.orderByDesc(Feedback::getCreateTime));
		List<MobileFeedbackVO> mobileFeedbackVOList = FeedbackStruct.INSTANCE.feedback2MobileVO(feedbackList);

		return R.ok(mobileFeedbackVOList);

	}


	/**
	 * Dapp保存用户反馈意见
	 * @param mobileFeedbackDTO 反馈意见
	 * @return R
	 */
	@ApiOperation(value = "Dapp保存用户反馈意见", notes = "Dapp保存用户反馈意见")
	@PostMapping("/app/saveUserFeedback")
	public R saveUserFeedback(@RequestBody MobileFeedbackDTO mobileFeedbackDTO){
		// 查询登录用户
		PigxUser user = SecurityUtils.getUser();
		if (user == null){
			return R.failed();
		}
		Feedback feedback = FeedbackStruct.INSTANCE.mobileDTO2Feedback(mobileFeedbackDTO);

		feedback.setUid(user.getId());
		return R.ok(feedbackService.save(feedback));
	}
}
